<template>
  <div v-show="!isMain && !isView" class="add-equip-detail">
    <px-scrollbar class="add-equip-content">
      <px-button style="margin: 16px 0 -4px" type="primary" icon="ArrowLeft" @click="backMainPage">返回</px-button>
      <EditDropDown dropdownTitle="基础信息">
        <template v-slot:content>
          <px-form ref="formRef" :inline="true" :model="formValue" :rules="rules" label-position="right" label-width="120px">
            <px-row>
              <px-col :span="8">
                <px-form-item label="工具借用单号" prop="toolBorrowCode">
                  <px-input v-model="formValue.toolBorrowCode" disabled placeholder="请输入工具借用单号" clearable />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="借用人" prop="toolBorrower">
                  <px-select-v2
                    v-model="formValue.toolBorrower"
                    filterable
                    clearable
                    :options="custodianList"
                    placeholder="请选择借用人"
                    @change="custodianChange"
                  />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="借用人电话" prop="toolBorrowerPhone">
                  <px-input v-model="formValue.toolBorrowerPhone" placeholder="根据选择的借用人自动带出" clearable />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="借用人科室" prop="className">
                  <px-select
                    v-model="formValue.className"
                    :disabled="classInfo && classInfo.length === 1"
                    placeholder="根据选择的借用人自动带出"
                    filterable
                    clearable
                  >
                    <px-option v-for="item in classNameList" :key="item.id" :label="item.name" :value="item.value" />
                  </px-select>
                </px-form-item>
              </px-col>
              <px-col :span="16">
                <px-form-item label="借出用途" prop="toolBorrowUse">
                  <px-input
                    v-model="formValue.toolBorrowUse"
                    type="textarea"
                    placeholder="请输入借出用途"
                    :autosize="{ minRows: 1, maxRows: 4 }"
                    maxlength="1000"
                    clearable
                  />
                </px-form-item>
              </px-col>
            </px-row>
          </px-form>
        </template>
      </EditDropDown>
      <EditDropDown dropdownTitle="借用工具">
        <template v-slot:content>
          <div style="width: 100%">
            <px-button type="primary" icon="plus" plain style="margin: -8px auto 8px" @click="dialogVisible = true">选择工具</px-button>
            <px-table :data="selectTableData" class="equip-table" size="small" height="calc(100vh - 600px)" border>
              <px-table-column fixed="left" type="index" width="50" label="序号" align="center" />
              <px-table-column fixed="left" prop="toolCode" label="工具编码" min-width="120" show-overflow-tooltip />
              <px-table-column prop="toolCategoryDesc" label="工具分类" min-width="100" show-overflow-tooltip />
              <px-table-column prop="toolName" label="工具名称" min-width="100" show-overflow-tooltip />
              <px-table-column prop="factoryAreaDesc" label="厂区" min-width="100" show-overflow-tooltip />
              <px-table-column prop="toolUnitDesc" label="工具单位" min-width="100" show-overflow-tooltip />
              <px-table-column prop="toolModel" label="型号/规格" min-width="120" show-overflow-tooltip />
              <px-table-column prop="brandVal" label="品牌" min-width="120" show-overflow-tooltip />
              <px-table-column prop="classNameDesc" label="工具科室" min-width="100" show-overflow-tooltip />
              <px-table-column prop="assetTagDesc" label="资产标签" min-width="120" show-overflow-tooltip />
              <px-table-column prop="custodianName" label="管理人" min-width="120" show-overflow-tooltip />
              <px-table-column fixed="right" label="操作" min-width="60" align="center">
                <template #default="scope">
                  <px-tooltip content="删除" placement="top">
                    <px-button link type="danger" icon="Delete" @click="handleDelete(scope.$index)" />
                  </px-tooltip>
                </template>
              </px-table-column>
            </px-table>
          </div>
        </template>
      </EditDropDown>
      <ToolList :visible="dialogVisible" @closeDialog="closeDialog" />
    </px-scrollbar>
    <div class="info-form-btns">
      <px-button @click="backMainPage">取消</px-button>
      <px-button type="primary" @click="handleSubmit(formRef)">保存</px-button>
    </div>
  </div>
</template>
<script setup lang="ts">
import { queryDictData } from "@/api/common";
import { addToolBorrowCode, getToolBorrowCode, getToolLedger } from "@/api/equip/toolManage";
import { getEmployeeIdAndName } from "@/utils/pengxi";
import EditDropDown from "@/views/all/equip/components/EditDropDown.vue";
import { PxMessage } from "px-ui";
import { computed, reactive, ref, toRefs, watch } from "vue";
import ToolList from "./ToolList.vue";

// 调用父级-返回主页、查询列表方法
const emits = defineEmits(["backMainPage", "queryTable"]);

// 父级传过来的值
const props = defineProps({
  // 主页面/详情页面
  isMain: {
    type: Boolean,
    default: false
  },
  // 查看or新增/编辑
  isView: {
    type: Boolean,
    default: false
  },
  toolBorrowId: {
    type: String,
    default: ""
  }
});
// 显示隐藏
const isMain = computed(() => props.isMain);
const isView = computed(() => props.isView);
// 页面本身的值
const formRef = ref();
const state = reactive<any>({
  formValue: {
    toolBorrowCode: ""
  },
  classNameList: [], // 工具科室下拉框
  custodianList: [], // 责任人下拉框
  selectTableData: [],
  dialogVisible: false,
  classInfo: {}
});
const { formValue, classNameList, custodianList, selectTableData, dialogVisible, classInfo } = toRefs(state);

// 表单校验规则
const rules = computed(() => ({
  toolBorrower: [{ required: true, message: "借用人不能为空", trigger: ["blur", "change"] }],
  className: [{ required: true, message: "借用人科室不能为空", trigger: ["blur", "change"] }]
}));

// 获取后端自动生成的工具编码
const getToolCode = async () => {
  const data = await getToolBorrowCode();
  formValue.value.toolBorrowCode = data;
};

// 字典
const queryDictValSelect = async () => {
  // const classNameData = await queryCurrentClassList(); // 工具科室下拉框
  // classNameList.value = classNameData;
  classNameList.value = await queryDictData({ typeCode: "className" });
};

// 监视isMain和isView值
watch(isMain, async val => {
  if (!val && !props.isView) {
    formRef.value?.resetFields();
    queryDictValSelect();
    custodianList.value = await getEmployeeIdAndName(["MACHINE", "WATER", "GAS", "ELECTRICTITY"]);
    getToolCode();
    const userInfo = JSON.parse(localStorage.getItem("userInfo"));
    classInfo.value = JSON.parse(localStorage.getItem("classList"));
    // 如果当前登录人在下拉列表里则给他默认值
    const filterItem = custodianList.value?.filter(item => item.userId === userInfo?.userId);
    if (filterItem?.length !== 0) {
      formValue.value.toolBorrower = userInfo?.userId;
      formValue.value.toolBorrowerPhone = userInfo?.phone;
      formValue.value.toolBorrowerName = filterItem[0]?.label;
      formValue.value.className = filterItem[0]?.deptName;
    }
    if (classInfo.value?.length === 1) {
      formValue.value.className = classInfo.value[0]?.code;
    }
    if (props.toolBorrowId) {
      const res = await getToolLedger({ id: props.toolBorrowId });
      if (res) {
        selectTableData.value = [res];
      }
    }
  }
});

// 关闭选择工具的弹窗并且拿到选择的数据
const closeDialog = (val?: any) => {
  if (val) {
    selectTableData.value = selectTableData.value?.concat(val)?.filter((obj, index, self) => {
      return self.map(x => x.id).indexOf(obj.id) === index;
    });
  }
  dialogVisible.value = false;
};

// 获取借用人的名字
const custodianChange = val => {
  const arr = custodianList.value.find(item => item.value === val);
  console.log(arr);
  if (arr) {
    formValue.value.toolBorrowerName = arr?.label;
    formValue.value.toolBorrowerPhone = arr?.phone;
    formValue.value.className = arr?.deptName;
  }
};

// 删除文件table的某一项
const handleDelete = index => {
  selectTableData.value.splice(index, 1);
};

// 返回主页面
const backMainPage = () => {
  formRef.value.resetFields();
  selectTableData.value = [];
  emits("backMainPage");
};

// 提交
const handleSubmit = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      const ids = selectTableData.value?.map(item => item.id);
      await addToolBorrowCode({ ...formValue.value, toolInfoIdList: ids });
      PxMessage({
        type: "success",
        message: "创建成功!"
      });
      selectTableData.value = [];
      emits("backMainPage");
      emits("queryTable");
    }
  });
};
</script>
<style lang="scss" scoped>
@import url("@/views/all/equip/scss/add-detail.scss");
</style>
